from django.db import models
from case_api.models import Case
from project.models import Project

class Suite(models.Model):
    STATUS_CHOICES = [
        ('ACTIVE', '激活'),
        ('INACTIVE', '未激活'),
    ]
    
    name = models.CharField('套件名称', max_length=32)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    description = models.TextField('套件描述', default='')
    status = models.CharField('套件状态', max_length=20, choices=STATUS_CHOICES, default='ACTIVE')
    case_api_list = models.ManyToManyField(Case, blank=True, verbose_name='测试用例')
    created_time = models.DateTimeField('创建时间', auto_now_add=True, null=True)
    updated_time = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = '测试套件'
        verbose_name_plural = '测试套件列表'
        
    def __str__(self):
        return self.name

    def case_api_count(self):
        """获取API用例数量"""
        return self.case_api_list.all().count()
    
    @property
    def case_count(self):
        """获取用例数量（用于序列化）"""
        return self.case_api_count()

class RunResult(models.Model):
    RUN_STATUS_CHOICES = [
        (0, "初始化"),
        (1, "准备开始"),
        (2, "正在执行"),
        (3, "生成报告中"),
        (4, "执行完毕"),
        (5, "执行出错"),
    ]
    suite = models.ForeignKey(Suite, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    path = models.TextField("用例路径")
    is_pass = models.BooleanField("测试通过", default=False)
    status = models.IntegerField("执行状态", choices=RUN_STATUS_CHOICES,default=0)

class SuiteExecutionRecord(models.Model):
    STATUS_CHOICES = [
        ('pending', '未执行'),
        ('running', '执行中'),
        ('success', '成功'),
        ('failed', '失败'),
    ]
    suite = models.ForeignKey(Suite, on_delete=models.CASCADE, related_name='executions')
    status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='pending')
    result = models.TextField(blank=True, null=True)
    report_url = models.CharField(max_length=255, blank=True, null=True)
    executed_cases = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"套件{self.suite.id}执行于{self.created_at}"